import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
// RSA 加密插件
import { JSEncrypt } from "jsencrypt";
import { getHttp, postHttp } from "../../api";
import { Notify } from "react-vant";
// 公钥
export const publicKey = `MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCuQd3gESx7VdIyRYUWjmjg61VIgUK6F45hClmqUMZ7xNiT5rlLM6e78osMvBF/yP7cVm7pK+NMCDWoVS1/AETpxJYqUlIC77ZAU8/MnP96IupnJL87vqhPcpdv7+VqLM38ls++yuD/F/HSoOQTv/leJh+dgE/4EYAJjOWFAbYfXwIDAQAB`;

// 加密方法
export const encryptedData = (publicKey, data) => {
  // 新建JSEncrypt对象
  const encryptor = new JSEncrypt();
  // 设置公钥
  encryptor.setPublicKey(publicKey); // publicKey为公钥
  // 加密数据
  return encryptor.encrypt(data); //data就是需要加密的密码
};

export interface LoginRawState {
  email: string;
  pwd: string;
}

// 登录 action
export const login = createAsyncThunk(
  "user/login",
  async (data: LoginRawState) => {
    // 密码加密 rsa
    data.pwd = encryptedData(publicKey, data.pwd) as string;
    // 请求
    const { status, result, message } = await postHttp(
      "health/user/v1/login",
      data
    );
    if (status === "0000") {
      Notify.show({ type: "primary", message });
      return result;
    } else {
      Notify.show({ type: "danger", message });
      return Promise.reject(message);
    }
  }
);

interface RegistRawState {
  email: string;
  code: string;
  pwd1: string;
  pwd2: string;
  invitationCode?: string;
}

// 注册 actions
export const regist = createAsyncThunk(
  "user/regist",
  async (data: RegistRawState) => {
    // 密码加密 rsa
    data.pwd1 = encryptedData(publicKey, data.pwd1) as string;
    data.pwd2 = data.pwd1;
    // 请求
    return await postHttp("health/user/v1/register", data);
  }
);
export const userInfo = {
  // 年龄
  age: -1,
  // 邮箱
  email: "",
  // 头部图片
  headPic: "",
  // 身高
  height: -1,
  // 用户id
  userId: -1,
  // 邀请码
  invitationCode: "-1",
  // 激光码
  jiGuangPwd: "",
  // 昵称
  nickName: "",
  // 会话id
  sessionId: "",
  // 性别
  sex: -1,
  // 用户名
  userName: "",
  // 体重
  weight: -1,
  // 不清楚
  whetherBingWeChat: -1,
  // 不清楚
  faceFlag: -1,
};

interface GetUserInfoState {
  userId: string;
  sessionId: string;
}
// 获取用户信息
export const getUserInfo = createAsyncThunk(
  "user/userinfo",
  async (params: GetUserInfoState) => {
    const resp = await getHttp(
      "/health/user/verify/v1/getUserInfoById",
      params
    );
    if (resp.status === "0000") return resp.result;
    else return Promise.reject();
  }
);

// 切片
const userSlice = createSlice({
  name: "userSlice",
  initialState: {
    // 用户信息
    userInfo: userInfo,
    // 登录态
    isLogin: false,
    // 首页搜索记录
    searchList: [] as string[],
    // 病友圈搜索历史记录
    patientCircleSearchList: [] as string[],
  },
  reducers: {
    addSearchList(state, action: PayloadAction<string>) {
      state.searchList = Array.from(
        new Set([action.payload, ...state.searchList])
      );
    },
    addpatientCircleSearchList(state, action: PayloadAction<string>) {
      state.patientCircleSearchList = Array.from(
        new Set([action.payload, ...state.patientCircleSearchList])
      );
    },
    removeSearchList(state, action: PayloadAction<string>) {
      state.searchList = state.searchList.filter((v) => v !== action.payload);
    },
    clearSearchList(state) {
      state.searchList = [];
    },
    userQuit(state) {
      state.isLogin = false;
      state.userInfo = userInfo;
    },
  },
  extraReducers: {
    [login.fulfilled.type](state, action) {
      state.isLogin = true;
      state.userInfo = action.payload;
    },
    [getUserInfo.fulfilled.type](state, action) {
      state.userInfo = {
        ...state.userInfo,
        ...action.payload,
      };
    },
  },
});

// 抛出reduce
export default userSlice.reducer;

export const {
  addSearchList,
  removeSearchList,
  clearSearchList,
  addpatientCircleSearchList,
  userQuit,
} = userSlice.actions;
